package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    // 查询单个博客
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        setBlogUserDetails(CollectionUtil.toList(blog));

        return Result.ok(blog);
    }

    // 查询热门博客
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();

        setBlogUserDetails(records);

        return Result.ok(records);
    }


    // 博客点赞
    @Override
    public Result likeBlog(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 判断是否已经点赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        if (score == null) {
            // 未点赞 点赞
            boolean updated = update().setSql("liked = liked + 1").eq("id", id).update();
            if (updated) {
                // 将点赞用户添加到Redis
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            } else {
                return Result.fail("点赞失败");
            }
        } else {
            // 已点赞 取消点赞
            boolean updated = update().setSql("liked = liked - 1").eq("id", id).update();
            if (updated) {
                // 将点赞用户从Redis移除
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            } else {
                return Result.fail("取消点赞失败");
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查询 top5点赞用户 ZRANGE key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok();
        }
        // 解析用户id
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", userIds);
        List<User> users = userService.query().in("id", userIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 封装成UserDTO
        // List<UserDTO> dtoList = new ArrayList<>();
        // 解法 1
        // users.forEach(user -> {
        //     dtoList.add(BeanUtil.copyProperties(user, UserDTO.class));
        //  });
        //解法 2
        List<UserDTO> userDTOS = users.stream()
                .map(u -> BeanUtil.copyProperties(u, UserDTO.class))
                .collect(Collectors.toList());
        // 根据查询到的用户id查询用户信息
        return Result.ok(userDTOS);
    }

    /**
     * 发布博客添加 Feed 流，发送到粉丝收件箱
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = this.save(blog);
        if (!isSuccess) {
            return Result.fail("笔记保存失败");
        }
        // 查询发布博客的人的粉丝 select * from tb_follow where follow_user_id = ?
        LambdaQueryWrapper<Follow> qw = new LambdaQueryWrapper<>();
        qw.select(Follow::getUserId).eq(Follow::getFollowUserId, user.getId());
        List<Follow> follows = followService.list(qw);
        if (follows == null || follows.isEmpty()) {
            return Result.ok();
        }
        follows.stream()
                .map(Follow::getUserId)
                .forEach(followId -> {
                    // 给粉丝发送消息
                    String key = FEED_KEY + followId;
                    stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
                });

        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询关注用户发布的博客
     *
     * @param lastMinTime
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long lastMinTime, Integer offset) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastMinTime, offset, 2);
        // 3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 4.解析数据 blogId、minTime（时间戳）、offset（上次查询的最小值的重复次数）
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        int offsetTemp = offset;
        long minTime = lastMinTime;

        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 获取博客id
            blogIds.add(Long.valueOf(tuple.getValue()));
            // 获取score（时间戳）
            long time = tuple.getScore().longValue();
            if (minTime == time) {
                offsetTemp++;
            } else {
                minTime = time;
                offsetTemp = 1;
            }
        }
        // 5.根据id查询blog
        String idStr = StrUtil.join(",", blogIds);
        LambdaQueryWrapper<Blog> qw = new LambdaQueryWrapper<>();
        qw.in(Blog::getId, blogIds)
                .last("ORDER BY FIELD(id," + idStr + ")");
        List<Blog> blogList = list(qw);
        if (blogList.isEmpty()) {
            return Result.fail("获取博客信息失败");
        }
        setBlogUserDetails(blogList);

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(offsetTemp);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }


    /**
     * 设置博客对应的用户信息和是否点赞
     *
     * @param records
     */
    private void setBlogUserDetails(List<Blog> records) {
        // 提取博客中的用户id
        Set<Long> userIds = records.stream()
                .map(Blog::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 批量查询用户
        List<User> users = userService.listByIds(userIds);


        // 构建用户ID到用户的映射
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        // 填充用户信息
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            if (userId != null && userMap.containsKey(userId)) {
                isBlogLiked(blog);
                User user = userMap.get(userId);
                blog.setIcon(user.getIcon());
                blog.setName(user.getNickName());
            }
        });

    }

    /**
     * 根据当前用户从Redis中判断是否点赞过该博客
     *
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询用户是否点赞
            return;
        }
        Long userId = user.getId();
        // 判断是否已经点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        blog.setIsLike(score != null);
    }
}
